﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace Microsoft.OpportunityPortal.CustomTaskWP
{
    [ToolboxItemAttribute(false)]
    public class CustomTaskWP : WebPart
    {
        public enum WorkflowType
        {
            Approve,
            Review
        };

        WorkflowType wfType = WorkflowType.Approve;
        string message = string.Empty;
        int taskCount = 0;

                // Creates a custom property that is an enum.
        // This property will be displayed as a drop-down list in the
        // property pane.
        [Category("Custom Properties")]
        [DefaultValue(WorkflowType.Approve)]
        [Microsoft.SharePoint.WebPartPages.FriendlyName("Task WorkFlow Type")]
        [Description("Select a task workflow type")]
        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        public WorkflowType WFType
        {
            get
            {
                return wfType;
            }
            set
            {
                wfType = value;
            }
        }

        // Creates a custom property that is an string.
        // This property will be displayed as a drop-down list in the
        // property pane.
        [Category("Custom Properties")]
        [DefaultValue("No Task to show in the panel")]
        [Microsoft.SharePoint.WebPartPages.FriendlyName("No Task Message")]
        [Description("Enter a no task message to be shown in the webpart")]
        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        public string NoTaskMessage
        {
            get
            {
                return this.message;
            }
            set
            {
                this.message = value;
            }
        }

        // Creates a custom property that is an int.
        // This property will be displayed as a drop-down list in the
        // property pane.
        [Category("Custom Properties")]
        [DefaultValue(10)]
        [Microsoft.SharePoint.WebPartPages.FriendlyName("Task Count")]
        [Description("Enter a non zero value to show the no of tasks")]
        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        public int TaskCount
        {
            get
            {
                return taskCount;
            }
            set
            {
                taskCount = value;
            }
        }

        protected override void CreateChildControls()
        {
            try
            {
                using (SPWeb web = SPContext.Current.Site.OpenWeb())
                {
                    SPList taskList = web.Lists["Tasks"];
                    HtmlTable table = new HtmlTable();
                    table.ID = "table";
                    HtmlTableRow hdrRow = new HtmlTableRow();
                    hdrRow.Attributes.Add("Class", "ms-viewheadertr ms-vhltr");
                    hdrRow.Attributes.Add("vAlign", "top");

                    HtmlTableCell cell = new HtmlTableCell("th");
                    cell.InnerText = "Title";
                    cell.Attributes.Add("Class", "ms-vh2");
                    cell.Attributes.Add("Scope", "col");
                    hdrRow.Cells.Add(cell);

                    // Insert status header
                    HtmlTableCell statuscell = new HtmlTableCell("th");
                    statuscell.InnerText = "Status";
                    statuscell.Attributes.Add("Class", "ms-vh2");
                    statuscell.Attributes.Add("Scope", "col");
                    hdrRow.Cells.Add(statuscell);

                    // Insert Opportunity Link
                    HtmlTableCell oppCell = new HtmlTableCell("th");
                    oppCell.InnerText = "Opportunity";
                    oppCell.Attributes.Add("Class", "ms-vh2");
                    oppCell.Attributes.Add("Scope", "col");
                    hdrRow.Cells.Add(oppCell);

                    SPQuery query = new SPQuery();
                    string taskTitle = string.Empty;

                    if (TaskCount > 0)
                    {
                        query.RowLimit = (uint)TaskCount;
                    }

                    if (wfType == WorkflowType.Approve)
                    {
                        query.Query = @"<Where>
                                  <And>
                                     <Contains>
                                        <FieldRef Name='Title' />
                                        <Value Type='Text'>approval</Value>
                                     </Contains>
                                     <Neq>
                                        <FieldRef Name='Status' />
                                        <Value Type='Choice'>Completed</Value>
                                     </Neq>
                                  </And>
                               </Where>
                               <OrderBy>
                                  <FieldRef Name='Created' Ascending='False' />
                               </OrderBy>";
                        taskTitle = "Please approve/reject the opportunity: ";
                    }
                    else
                    {
                        query.Query = @"<Where>
                                  <And>
                                     <Contains>
                                        <FieldRef Name='Title' />
                                        <Value Type='Text'>review</Value>
                                     </Contains>
                                     <Neq>
                                        <FieldRef Name='Status' />
                                        <Value Type='Choice'>Completed</Value>
                                     </Neq>
                                  </And>
                               </Where>
                               <OrderBy>
                                  <FieldRef Name='Created' Ascending='False' />
                               </OrderBy>";
                        taskTitle = "Please review the opportunity: ";
                    }

                    SPListItemCollection itemcolln = taskList.GetItems(query);
                    int itemCount = itemcolln.Count;
                    int counter = 0;

                    if (itemCount > 0)
                    {
                        table.Rows.Add(hdrRow);
                    }
                    else
                    {
                        Label noTaskMessageLbl = new Label();
                        noTaskMessageLbl.Text = NoTaskMessage;
                        this.Controls.Add(noTaskMessageLbl);
                    }

                    while (itemCount > 0)
                    {
                        itemCount--;
                        SPListItem item = itemcolln[counter++];
                        SPContentTypeId contentTypeid = item.ContentTypeId;
                        Guid listiD = item.ParentList.ID;
                        int listitemID = item.ID;
                        string taskURL = web.Url + "/_layouts/WrkTaskIP.aspx?List=" + listiD.ToString() + "&ID=" + listitemID + "&ContentTypeId=" + contentTypeid.ToString();

                        if (taskList.Fields.ContainsField("WorkflowLink") && taskList.Fields.ContainsField("Related Content")
                            && taskList.Fields.ContainsField("Status") && item["WorkflowLink"] != null && item["Status"] != null)
                        {
                            string opportunityitemURL = item["WorkflowLink"].ToString();
                            string wfStatus = item["Status"].ToString();

                            // Get the list item name
                            string[] oppItem = opportunityitemURL.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                            if (oppItem.Length == 2)
                            {
                                string oppName = oppItem[1];
                                string oppLink = oppItem[0];

                                HtmlTableRow row = new HtmlTableRow();
                                HtmlTableCell linkCell = new HtmlTableCell();

                                HtmlAnchor titleLink = new HtmlAnchor();
                                titleLink.HRef = taskURL;
                                titleLink.InnerText = taskTitle + oppName;
                                titleLink.Attributes.Add("Class", "ms-vh2");
                                linkCell.Controls.Add(titleLink);

                                HtmlGenericControl lit = new HtmlGenericControl("div");
                                HtmlTableCell statusCell = new HtmlTableCell();
                                lit.InnerText = wfStatus;
                                lit.Attributes.Add("Class", "ms-vb2");
                                statusCell.Controls.Add(lit);

                                HtmlTableCell oppLinkCell = new HtmlTableCell();
                                HtmlAnchor opportunitylink = new HtmlAnchor();
                                opportunitylink.HRef = oppLink;
                                opportunitylink.InnerText = oppName;
                                opportunitylink.Attributes.Add("Class", "ms-vh2");
                                oppLinkCell.Controls.Add(opportunitylink);

                                row.Cells.Add(linkCell);
                                row.Cells.Add(statusCell);
                                row.Cells.Add(oppLinkCell);
                                table.Rows.Add(row);
                            }
                        }
                    }

                    if (counter > 0)
                    {
                        this.Controls.Add(table);
                    }
                }
            }
            catch (SPException expn)
            {
                Dictionary<string, string> errorLog = new Dictionary<string, string>();
                errorLog.Add("Title", "Error_" + DateTime.Now.ToLongTimeString());
                errorLog.Add("Description", string.Format("{0}, {1}", expn.Message, expn.StackTrace));
                errorLog.Add("EventType", "Error");

                SPOperations.AddUpdateListItem(SPContext.Current.Site.Url, "Logger", errorLog, SPEventType.Add);
            }
        }
    }
}
